<?php

namespace app\services;

use plugin\admin\app\model\Order;
use plugin\admin\app\model\OrderGoods;
use plugin\admin\app\model\OrderMessage;

class OrderMessageService
{
    public static function add($id, $messageType = OrderMessage::TYPE_SHIPPING)
    {
        $order = Order::where('id', $id)->first();

        if (!$order) {
            throw new \Exception('订单不存在');
        }

        $message = OrderMessage::getDescText($messageType);

        return OrderMessage::insertGetId([
            'user_id' => $order['user_id'],
            'order_no' => $order['order_no'],
            'desc' => $message,
            'created_time' => date('Y-m-d H:i:s'),
            'is_read' => 0
        ]);
    }

    public static function list($page = 1, $length = 10)
    {
        $offset = ($page - 1) * $length;

        $messages = OrderMessage::where('user_id', get_user_id())->offset($offset)->limit($length)->orderBy('id', 'desc')->get()->toArray();
        $orderNos = array_column($messages, 'order_no');

        $orderGoodsList = OrderGoods::whereIn('order_no', $orderNos)->get()->toArray();

        foreach ($messages as $key=>$message) {
            foreach ($orderGoodsList as $orderGoods) {
                if ($orderGoods['order_no'] == $message['order_no']) {
                    $message['order_goods_info'] = $orderGoods;
                    break;
                }
            }

            $messages[$key] = $message;
        }

        return $messages;
    }

    public static function markRead($orderNo)
    {
        OrderMessage::where('user_id', get_user_id())->where('order_no', $orderNo)->update(['is_read' => 1]);
    }
}